//
//  SelectTopicController.swift
//  选择话题
//
//  Created by smile on 2019/7/1.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入发布订阅框架
import SwiftEventBus

class SelectTopicController: BaseTitleController {
    
    
    /// 列表控件
    @IBOutlet weak var tableView: UITableView!
    
    /// 列表数据
    var dataArray:[Topic] = []
    
    override func initViews() {
        super.initViews()
        
        setTitle("选择话题")
        
        //注册cell
        tableView.register(UINib(nibName: TopicCell.NAME, bundle: nil), forCellReuseIdentifier: TopicCell.NAME)
    }
    
    override func initDatas() {
        super.initDatas()
        
        //请求话题
        Api.shared
            .topics()
            .subscribeOnSuccess { (data) in
                if let data = data?.data?.data {
                self.dataArray = self.dataArray+data
                self.tableView.reloadData()
            }
        }.disposed(by: disposeBag)
    }
    

    /// 启动方法
    ///
    /// - Parameter nav: <#nav description#>
    static func start(_ nav:UINavigationController) {
        //创建控制器
        let controller = nav.storyboard!.instantiateViewController(withIdentifier: "SelectTopic")
        
        nav.pushViewController(controller, animated: true)
    }

}

// MARK: - 列表数据源和代理
extension SelectTopicController:UITableViewDataSource,UITableViewDelegate {
    
    /// 返回有多少个
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回Cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //获取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: TopicCell.NAME, for: indexPath) as! TopicCell
        
        //绑定数据
        cell.bindData(dataArray[indexPath.row])
        
        //返回cell
        return cell
    }
    
    
    /// cell点击事件
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //获取当前点击的数据
        let data = dataArray[indexPath.row]
        
        //把数据发送出去
        SwiftEventBus.post(ON_SELECT_TOPIC, sender: data)
        
        //关闭界面ON_ON_
        navigationController!.popViewController(animated: true)
    }
    
}
